package com.express.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.express.basic.constant.ExpressConstant;
import com.express.basic.exception.ExpressException;
import com.express.basic.token.DefaultTokenManager;
import com.express.basic.util.StringEscapeEditor;
import com.express.param.BaseModelReq;
import com.express.param.MsgResponse;

@Service
public abstract class AbstractController {

	
	private static final Logger logger = LoggerFactory.getLogger(AbstractController.class);
	

	@Autowired
	private DefaultTokenManager tokenManager;

	@ExceptionHandler
	@ResponseBody
	public MsgResponse handle(Exception e) {
		
		
		if(e instanceof IOException){
			logger.error("IOException", e);
			return new MsgResponse(ExpressConstant.MsgCode.SYSTEM_ERROR);
		}else if(e instanceof ExpressException){
			logger.error("业务异常", e.getMessage());
			return new MsgResponse(((ExpressException) e).getCode(),((ExpressException) e).getMessage());
		}else if(e instanceof BindException){
			BindingResult result = ((BindException) e).getBindingResult();
			List<ObjectError> list = result.getAllErrors();
			ObjectError oe = list.get(0);
			logger.error("参数异常:"+oe.getDefaultMessage());
			return new MsgResponse(ExpressConstant.MsgCode.SYSTEM_ERROR.getCode(),oe.getDefaultMessage());
		}else if(e instanceof MethodArgumentNotValidException){
			String msg = ((MethodArgumentNotValidException)e).getBindingResult().getAllErrors().get(0).getDefaultMessage();
			logger.error("参数异常:"+ msg);
			return new MsgResponse(ExpressConstant.MsgCode.SYSTEM_ERROR.getCode(),msg);
		}
		else{
			logger.error("系统异常", e);
			return new MsgResponse(ExpressConstant.MsgCode.SYSTEM_ERROR);
		}
	}
	
	
	/**
	 * 网站sql注入，script注入等的防护。
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder,HttpServletRequest request) {
		binder.setAutoGrowCollectionLimit(5000);
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false, false));
	}
	
	/**
	 * 
	* @Title: needToken 
	* @Description: 必须校验
	* @param @param req
	* @param @param request    
	* @return void    
	* @throws
	 */
	public void needToken(BaseModelReq req,HttpServletRequest request){
		String headerValue = request.getHeader(ExpressConstant.HEADER_TOKEN);
		if(StringUtils.isBlank(headerValue))
			throw new ExpressException(ExpressConstant.MsgCode.TOKEN_ERROR);
		
		int userId = tokenManager.getUserId(headerValue);
		if(userId > 0)
			req.setUserId(userId);
		else
			throw new ExpressException(ExpressConstant.MsgCode.TOKEN_ERROR);
		
	}

	
	
}
